package com.github.xzb617.rpc.loadbalancer.strategy;

import com.github.xzb617.rpc.entity.Server;
import com.github.xzb617.rpc.loadbalancer.AbstractLoadBalancer;
import java.util.List;
import java.util.Random;

/**
 * 随机策略
 */
public class RandomLoadBalancer extends AbstractLoadBalancer {

    private final Random random;

    public RandomLoadBalancer() {
        this.random = new Random();
    }

    public Server chooseServer(List<Server> servers) {
        int size = servers.size();
        int position = this.acquireRandomPosition(size);
        return servers.get(position);
    }

    /**
     * 随机取得一个Server的下标
     * @param size 服务列表的容量
     * @return
     */
    private int acquireRandomPosition(int size) {
        return this.random.nextInt(size);
    }
}
